var gulp = require("gulp");
var gulp_min_css = require("gulp-minify-css");
var gulp_sass = require("gulp-sass");
var gulp_plumber = require("gulp-plumber");
var gulp_tinypng = require("gulp-tinypng");
var gulp_uglify = require("gulp-uglify");
var browser_sync = require("browser-sync").create();
var gulp_copy = require("gulp-copy");
var gulp_autoprefixer = require("gulp-autoprefixer");
var gulp_babel = require("gulp-babel");
//自动刷新浏览器
gulp.task('bsync', function() {
    browser_sync.init({
//  	port:Math.floor(Math.random()*9999)+1000,   //产生随机端口
        server: {
            baseDir: "./"   //根地址
        }
    });
    gulp.watch("sass/**/*.scss",['sass']).on("change", browser_sync.reload);
    gulp.watch("*.html").on("change", browser_sync.reload);
});

//sass转化css
gulp.task('sass',function(){
	return gulp.src('./sass/**/*.scss')
			   .pipe(gulp_sass().on('error',gulp_sass.logError))
			   .pipe(gulp.dest('./css'));
})

//css压缩
gulp.task("mincss",function(){//定义任务
	//具体事情
	//管道模式
	gulp.src('./sass/**/*.scss')
		.pipe(gulp_plumber())
		.pipe(gulp_sass())
		.pipe(gulp_min_css({
			keepSpecialComments: '*'  //保留所有特殊前缀
		}))
		.pipe(gulp_autoprefixer({
			browsers: ['last 2 versions', 'Android >= 4.0','iOS 7','last 3 Safari versions'],
			cascade: false
		}))

		.pipe(gulp.dest('./dist/css'))
})

//实时监听sass文件，并转化
gulp.task("watchscss",function(){
	gulp.watch('./sass/**/*.scss',["mincss"])
})
//图片压缩
gulp.task("minimg",function(){
	gulp.src('./img/**/*.*')
		.pipe(gulp_plumber())
		.pipe(gulp_tinypng("8xUS5CwNCUPDIqvpWg6eIbvJGI05a6h0"))
		.pipe(gulp.dest('./dist/img'))
})
//js压缩
gulp.task("minjs",function(){
	gulp.src("src/js/**/*.js")
		.pipe(gulp_babel({
			presets:["env"]
		}))
		.pipe(gulp_uglify())
		.pipe(gulp.dest('dist/js'))
})
//复制文件
gulp.task("copy",function(){
	gulp.src('*.html').pipe(gulp_copy('./src'));
	gulp.src('./img/**/*').pipe(gulp_copy('./src'));
	gulp.src('./css/**/*.css').pipe(gulp_copy('./src'));
	gulp.src('./js/**/*.js').pipe(gulp_copy('./src'));
	gulp.src('./sass/**/*.scss').pipe(gulp_copy('./src'));
})

//定义一键开发模式，开发版
gulp.task("dev",["bsync"]);

//定义一键生成模式,正式版
gulp.task("pro",["mincss","minjs","minimg"]);
